<?php
// WARNING: this will work only in PHP5
// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();
require_once(DOKU_INC.'phpincludes/ACC_Form_Base.php');

/**
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Stephane Chamberland <dokuwiki@meteokid.ca>
 * @date       2009-01-22
 */
class ACC_Form_KF extends ACC_Form_Base {

    var $mailTo = 'keenereserve@accmontreal.ca';
    var $mailToAllowed = array('keenereserve@accmontreal.ca');
    //var $mailTo = 'web@accmontreal.ca';
    //var $mailToAllowed = array('web@accmontreal.ca');
    var $mailToField = 'to_email';
    var $mailFromField = 'from_email';
    var $mailFromNameField = 'from_name';
    var $mailSubjectPrefix = '[KF reserv] ';

    var $mailSubjectFmtName = 'mailSubjectFmt';
    var $mailBodyFmtName = 'mailBodyFmt';

    var $metaFileSuffix = 'keene';
    var $metaFileid = '__keene';

    var $langArray = array(
        'fr' => array(
            'mailSent'       => 'Votre message a &eacute;t&eacute; envoy&eacute;',
            'mailSentError'  => "Erreur d'envoie, SVP contacter l'administrateur a ",
            'formDescFmt' => 'name keenefarm_reserv
action metafile keenefarm
Thanks "Merci d\'avoir fait une reservation pour Keene Farm. Keene Farm est gere par des benevoles, SVP allouer au moins 48h avant de recevoir une confirmation."
Fieldset "Informations personelles"
Textbox "Nom" #80 &from_name
email "E-Mail" #80 &from_email
phone "Telehone" #40 &from_phone
select "Club (Affiliation)" "None/Other|ACC_Montreal|ACC_Others" ="None/Other" &club
textbox "Numero de Membre (ACC)" ! #20 &club_nb
textbox "Immatriculation (Prov/Etat et Numero)" #80 &car
Fieldset "Details de la Reservation"
const uid __uid__
const  reserv reservation
const status new
const lang fr
select "Type" "Camping|Cabin" =Camping &cabin
date "Date (1ere nuit) [YYYY-MM-DD]" "=__date_def__" ">__date_min__" "<__date_max__" #20 &date
select "Nombre de nuits" "1|2|3|4|5|6|7" =1 &nights
static "SVP preciser le nombre de personnes dans votre groupe incluant vous meme en separant: Membres (ACC), Non-Membres et enfants de moins de 16 ans. Pour de grand groupes, SVP contacter les coor. de Keene Farm."
select "Nb. de Membres" "Zero|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15" &people_member
select "Nb. de Non-Membres" "Zero|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15" ="Zero" &people_guests
select "Nb. d\'enfants de moins de 16 ans" "Zero|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15" ="Zero" &people_children
static "Pourquoi etre gardien? Votre s&eacute;jour pourrait etre gratuit! [<a href=\'/fr/huts/custodian_handbook\' target=\'_new\'>d&eacute;tails</a>]"
select "Vous portez-vous volontaire pour etre Gardien?" "Oui|Non"  &custodian
leftcheck "SVP lire le <a href=\'http://www.accmontreal.ca/_doc/keene_visitor_handbook_fr.pdf\' target=\'_new\'>Guide des visiteurs de Keene Farm</a> et cocher le case suivante pour confirmer que vous l\'avez lu." &handbook
leftcheck "Cocher la case a gauche si vous desirez recevoir des courriels promotionels." =yes ! &promo
textarea "Questions/Commentaires?" ! x3 #5000 &msg
submit "Soumettre votre Reservation" ',
            'mailSubjectFmt' => '__cabin__ __reserv__ for __from_name__ on __date__ for __nights__ nights, __people__ people (__people_member__ members, __people_guests__ guests, __people_children__ children)',
            'mailBodyFmt' => 'Keene Farm __reserv__ request
Submited by __from_name__ <__from_email__>
==== Details ====
__ACC_Form_list_all__
=============',
             'msg_camping'    => '
Merci d\'avoir fait une reservation pour le camping a Keene Farm.<br />
Votre reservation est maintenant confirmee (Numero de Confirmation __uid__).<br />
<br />
Details:<br />
Reservation pour le Camping a Keene Farm le __date__ pour __nights__ nuit(s), __people_member__ membres, __people_guests__ non-membres, __people_children__ enfants<br />
Faite par __from_name__ le __now__<br />
<br />
Pour les indications pour vous rendre a Keene Farm, voir la carte sur
<a class="urlextern" href="http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11">Google maps</a><br />
<a class="urlextern" href="http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11">
http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11</a><br />
<br />
Notez que <b>les membres doivent avoir leur carte en main</b> puisque le gardien en fera la verification.<br />
<b>SVP signer le registre des votre arrive a Keene Farm et faites votre payement a la borne d\'auto enregistrement (montant exacte ou cheque au nom de "ACC Montreal")</b> qui est situee pres de la pompe a eau et du garage.<br />
Le montant total pour votre sejour sera de: __total_cost__$<br />
<br />
<em>SVP imprimer ou sauvegarder cette confirmation pour reference ulterieur.</em>.<br />',
            'msg_cabin'    => '
Merci d\'avoir fait une reservation pour le refuge a Keene Farm.<br />
Votre reservation devrait etre confirmee sous peu (minimum de 48h) (Numero de Reference __uid__).<br />
<br />
Keene Farm est gere par des benevoles,<br /> SVP allouer au moins 48h avant de recevoir une confirmation.</b><br />
<br />
Details:<br />
Reservation pour le Refuge a Keene Farm le __date__ pour __nights__ nuit(s), __people_member__ membres, __people_guests__ non-membres, __people_children__ enfants<br />
Faite par __from_name__ le __now__<br />
<br />
Notez que <b>les membres doivent avoir leur carte en main</b> puisque le gardien en fera la verification.<br />
Les indications pour se rendre a Keene Farm vous seront communiquees avec la confirmation.<br />
<b>
VP signer le registre des votre arrive a Keene Farm et faites votre payement a la borne d\'auto enregistrement (montant exacte ou cheque au nom de "ACC Montreal")</b> qui est situee pres de la pompe a eau et du garage.<br />
Le montant total pour votre sejour sera de: __total_cost__$<br />
<br />
<em>SVP imprimer ou sauvegarder cette confirmation pour reference ulterieur.</em>.<br />',
        'error_nb_people' => 'SVP indiquer le nombres de personnes dans votre groupe incluant vous meme.',
        'error_club_nb' => 'SVP fournir votre numero de membre ACC ou bien selectionner None/Other',
        'error_nb_members' => 'SVP fournir les information sur votre affiliation (club and numero) ou bien remplacer le "Nombre de Membres" par le nombre equivalent de "Non-Membres".',
        'error_no_adult' => 'Un membre adulte doit accompagner les enfants. SVP preciser un "Nombre de Membres" plus grand que Zero'
        ),
        'en' => array(
            'mailSent'       => 'Your message was sent sucessfully',
            'mailSentError'  => 'There was an error sending your email, please contact the admin at ',
            'formDescFmt' => 'name keenefarm_reserv
action metafile keenefarm
Thanks "Thanks for making a reservation at Keene Farm. This is managed by volunteers, please allow at least 48h for a confirmation."
Fieldset "Your Personal Details"
Textbox "Name" #80 &from_name
email "E-Mail" #80 &from_email
phone "Phone" #40 &from_phone
select "Club Affiliation" "None/Other|ACC_Montreal|ACC_Others" ="None/Other" &club
textbox "Membership Number" ! #20 &club_nb
textbox "Car License (Prov/State and number)" #80 &car
Fieldset "Reservation Details"
const uid __uid__
const  reserv reservation
const status new
const lang en
select "Type of Accommodation" "Camping|Cabin" =Camping &cabin
date "Date (1st night) [YYYY-MM-DD]" "=__date_def__" ">__date_min__" "<__date_max__" #20 &date
select "nb of nights" "1|2|3|4|5|6|7" =1 &nights
static "Please specify the number of people in your party (including yourself) split in: members (ACC), Non-Members and children under 16 years old. For large groups, please contact the Keene Farm rep."
select "Nb. members" "Zero|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15" &people_member
select "Nb. non-members" "Zero|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15" ="Zero" &people_guests
select "Nb. children under 16" "Zero|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15" ="Zero" &people_children
static "Why volunteer to be a custodian? Your stay at Keene Farm could be FREE! [<a href=\'/en/huts/custodian_handbook\' target=\'_new\'>details</a>]"

select "Do you volunteer to be a custodian?" "Yes|No"  &custodian
leftcheck "Please read the <a href=\'http://www.accmontreal.ca/_doc/keene_visitor_handbook_en.pdf\' target=\'_new\'>Keene Visitor handbook</a> and check the box on the left to confirm you did" &handbook
leftcheck "Check the box on the left if you wish to receive promotional emails." =yes ! &promo
textarea "Questions/Comments?" ! x3 #5000 &msg
submit "Submit your Reservation" ',
            'mailSubjectFmt' => '__cabin__ __reserv__ for __from_name__ on __date__ for __nights__ nights, __people__ people (__people_member__ members, __people_guests__ guests, __people_children__ children)',
            'mailBodyFmt' => 'Keene Farm __reserv__ request
Submited by __from_name__ <__from_email__>
==== Details ====
__ACC_Form_list_all__
=============',
             'msg_camping'    => '
Thank you for making a camping reservation at Keene Farm.<br />
Your reservation is now confirmed (Confirmation number __uid__).<br />
<br />
Details:<br />
Reservation at Keene Farm camping on __date__ for __nights__ night(s), __people_member__ members, __people_guests__ guests, __people_children__ children<br />
Made by __from_name__ on __now__<br />
<br />
Directions to Keene Farm can be found on <a class="urlextern" href="http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11">Google maps</a><br />
<a class="urlextern" href="http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11">
http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11</a><br />
<br />
<b>Members must bring their cards</b> as the custodian will verify them.<br />
<b>Upon your arrival at Keene Farm, please register and pay (exact change or cheque to "ACC Montreal") at the Iron Ranger</b> next to the water pump and of the garage.<br />
The total amount for your stay will be: __total_cost__$<br />
<br />
<em>You may want to print (or save) this confirmation for later reference</em>.<br />',
            'msg_cabin'    => '
Thank you for making a cabin reservation at Keene Farm.<br />
Your reservation is pending confirmation (Reference number __uid__).<br />
<br />
This facility is managed by volunteers.<br />
<b>Please allow at least 48h for a confirmation.</b><br />
<br />
Details:<br />
Reservation at Keene Farm cabin on __date__ for __nights__ night(s), __people_member__ members, __people_guests__ guests, __people_children__ children<br />
Made by __from_name__ on __now__<br />
<br />
<b>Please note that members must bring their cards</b> as the custodian will verify them.<br />
Directions to Keene Farm will be provided with your confirmation.<br />
<b>Upon your arrival at Keene Farm, please register and pay (exact change or cheque to "ACC Montreal") to the custodian or at the Iron Ranger</b> next to the water pump.<br />
The total amount for your stay will be: __total_cost__$<br />
<br />
<em>You may want to write down the reference number (__uid__) for later query or cancelation</em>.<br />',
        'error_nb_people' => 'Please specify the number of people in your party (including yourself)',
        'error_club_nb' => 'Please provide your membership number or select None/Other',
        'error_nb_members' => 'Please provide member info (club and number) or change "nb. members" to "nb. non-members" ',
        'error_no_adult' => 'An adult must accompany childens, please specify "nb. members" or "nb. guests" greater than zero'
        )
    );

    var $kf_rates = array(
            'Camping' => array(
                'people_member' => 7,
                'people_guests' => 12,
                'people_children' => 0.),
            'Cabin' => array(
                'people_member' => 15,
                'people_guests' => 25,
                'people_children' => 0)
            );


    function _totalCost($values) {
        $amount = 0;
        //echo '<pre>';
        $cabin = isset($values['cabin']) ? $values['cabin']: 'Cabin';
        foreach(array('people_member','people_guests','people_children') as $k) {
            if(isset($values[$k]) && is_numeric($values[$k]))
                $amount += ($values[$k] * $this->kf_rates[$cabin][$k]);
            //echo $k.':'.$values2['cabin'].':'.$values2[$k] .'*'.$this->kf_rates[$values2['cabin']][$k].'='.$amount."\n";
        }
        $k = 'nights';
        if (isset($values[$k]) && is_numeric($values[$k]))
            $amount *= $values[$k];
        //echo 'nights:'.$values2['nights'].'*='.$amount."\n";
        //echo '</pre>';
        return $amount;
    }

    function _totalPeople($values) {
        $nb = 0;
        foreach(array('people_member','people_guests','people_children') as $k) {
            if(isset($values[$k]) && is_numeric($values[$k])) $nb += $values[$k];
        }
        return $nb;
    }

    function _getFormDescFieldsVals($formDescFmtName) {
        //only one possible format, ignore $formDescFmtName
        //TODO: in admin mode, min/max are infinity
        $nowStamp = mktime(0, 0, 0, date("m")  , date("d"), date("Y"));
        $now = date('Y-m-d',$nowStamp);
        $dtime1 = 3600*36; //36h
        $dtime2 = 3600*24*90; // 3 months
        $mindate = date('Y-m-d',$nowStamp + $dtime1);
        $maxdate = date('Y-m-d',$nowStamp + $dtime2);

        return array(
            '__uid__' => uniqid(),
            '__date_def__' => $mindate,
            '__date_min__' => $mindate,
            '__date_max__' => $maxdate
        );
    }

    function _postcheckpost($data) {
        $errors = array();
        $values = $this->buro->_collectpost($data);

        // [nb>0]
        $nb = $this->_totalPeople($values);
        if ($nb <= 0) {
            foreach(array('people_member','people_guests','people_children') as $k)
                $errors[$k] = 1;
            msg($this->getLang('error_nb_people'),-1);
        }
        // [club:number]
        if ($values['club']!='None/Other' && !$values['club_nb']) {
            $errors['club'] = 1;
            $errors['club_nb'] = 1;
            msg($this->getLang('error_club_nb'),-1);
        }
        //[nb_member:affiliation]
        if ($values['club']=='None/Other' && $values['people_member'] > 0) {
            $errors['club'] = 1;
            $errors['people_member'] = 1;
            msg($this->getLang('error_nb_members'),-1);
        }
        //[nb_child:nb_member/guests]
        if ($values['people_children']>0 && $values['people_children'] == $nb) {
            foreach(array('people_member','people_guests','people_children') as $k)
                $errors[$k] = 1;
            msg($this->getLang('error_no_adult'),-1);
        }

        return $errors;
    }

    function _preActionValuesMods($values) {
        $values['people'] = $this->_totalPeople($values);
        $values['total_cost'] = $this->_totalCost($values);
        if(!isset($values['now'])) $values['now'] = date('c');
        if(!isset($values['status'])) $values['status'] = 'new';
        return $values;
    }


    function _action_ok($data,$thanks) {
        $values = $this->buro->_collectpost($data);
        if (stripos($values['cabin'],'camping') !== false) $values['status'] = confirmed;

        $metaFile = $this->_metaFile_get($this->metaFileid);
        $metaFile = $this->_metaFile_add($metaFile,$values) ;
        $ok = $this->_metaFile_save($metaFile,$this->metaFileid);

        if($ok) $ok = $this->_sendMail($values);

        if ($ok) {
            $msg = $this->getLang('msg_cabin');
            if (stripos($values['cabin'],'camping') !== false) $msg = $this->getLang('msg_camping');
            $msg2 = $this->_str_replace_from_values($msg,$values);

            $fromName = 'ACC/CAC Montreal';
            $fromEmail = $this->mailTo;
            $from = $fromName.' <'.$fromEmail.'>';

            $toName = $values['from_name'];
            $toEmail = $values['from_email'];
            $to .= $toName.' <'.$toEmail.'>';

            $subject = 'ACC/CAC Montreal - Keene Farm, Reservation';
            $body = $this->_stripHTMLtags($msg2);
            $ok = mail_send($to,$subject, $body, $from);

            return $msg2;
        }
        msg($this->getLang('mailSentError'));
        return false;
    }

}

$my_contact_form = new ACC_Form_KF($this);
print($my_contact_form->_action_show_form());
